package com.liaowei.post.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liaowei.common.Constants;
import com.liaowei.common.ErrorCode;
import com.liaowei.exception.CustomerException;
import com.liaowei.model.domain.SpecialColumn;
import com.liaowei.post.mapper.SpecialColumnMapper;
import com.liaowei.post.model.param.SaveSpecialColumnParam;
import com.liaowei.post.model.param.SpecialColumnManagePageParam;
import com.liaowei.post.model.param.SpecialColumnStatusParam;
import com.liaowei.model.vo.SpecialColumnVO;
import com.liaowei.post.service.SpecialColumnService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* @author LindaMan
* @description 针对表【wy_special_column(专栏表)】的数据库操作Service实现
* @createDate 2023-05-11 08:31:59
*/
@Service
@RequiredArgsConstructor
public class SpecialColumnServiceImpl extends ServiceImpl<SpecialColumnMapper, SpecialColumn>
    implements SpecialColumnService{

    private final SpecialColumnMapper specialColumnMapper;


    // 转换VO
    public SpecialColumnVO toSpecialColumnVO(SpecialColumn column){
        SpecialColumnVO vo = new SpecialColumnVO();
        BeanUtil.copyProperties(column, vo);
        // 查询访问量
        Integer accessNumber = specialColumnMapper.selectPostAccessNumber(column.getId());
        vo.setAccessNumber(accessNumber);
        // 查询评论数
        Integer commentNumber = specialColumnMapper.selectPostCommentNumber(column.getId());
        vo.setCommentNumber(commentNumber);
        return vo;
    }


    /**
     * 查询全部的专栏
     * @return List<SpecialColumn>
     */
    @Override
    public List<SpecialColumn> searchSpecialColumnList() {
        List<SpecialColumn> list = specialColumnMapper.
                selectList(Wrappers.lambdaQuery(SpecialColumn.class).eq(SpecialColumn::getStatus, 1));
        return Optional.ofNullable(list).orElse(new ArrayList<>());
    }

    /**
     * 查询热门专栏
     * @return List<SpecialColumnVO>
     */
    @Override
    public List<SpecialColumnVO> searchHotColumnVOList() {
        List<SpecialColumnVO> columnList = specialColumnMapper.selectHotColumnVOList();
        return Optional.ofNullable(columnList).orElse(new ArrayList<>());
    }

    /**
     * 查询最近访问的帖子所属的专栏
     * @param userId 用户id
     * @return List<SpecialColumn>
     */
    @Override
    public List<SpecialColumn> searchColumnListByUserId(Long userId) {
        List<SpecialColumn> columnList = specialColumnMapper.selectAccessColumn(userId);
        return Optional.ofNullable(columnList).orElse(new ArrayList<>());
    }

    /**
     * 根据id查询SpecialColumnVO
     * @param id 专栏id
     * @return 专栏vo
     */
    @Override
    public SpecialColumnVO searchColumnVOById(Long id) {
        // 查询专栏
        SpecialColumn column = specialColumnMapper.selectById(id);

        // 转换vo并返回
        return toSpecialColumnVO(column);
    }

    /**
     * 后台-分页查询专栏
     * @param pageParam 分页参数
     * @return IPage<SpecialColumnVO>
     */
    @Override
    public IPage<SpecialColumnVO> searchColumnManagePage(SpecialColumnManagePageParam pageParam) {
        // 分页参数预处理
        int pageNum = pageParam.getPageParam().getPageNum();
        int pageSize = pageParam.getPageParam().getPageSize();

        // 构造分页构造器
        IPage<SpecialColumn> page = new Page<>(pageNum,pageSize);
        IPage<SpecialColumnVO> VOPage = new Page<>();

        // 构造查询构造器
        LambdaQueryWrapper<SpecialColumn> wrapper = Wrappers.lambdaQuery(SpecialColumn.class)
                .like(SpecialColumn::getName, pageParam.getName())
                .eq(SpecialColumn::getStatus,1);

        // 分页查询
        specialColumnMapper.selectPage(page,wrapper);
        BeanUtil.copyProperties(page,VOPage,"records");


        // 转换VO
        List<SpecialColumnVO> voList = page.getRecords().stream()
                .map(this::toSpecialColumnVO).collect(Collectors.toList());

        // 封装page
        VOPage.setRecords(voList);

        return VOPage;
    }

    /**
     * 分页查询专栏
     * @param pageNum 当前页
     * @param pageSize 分页大小
     * @return IPage<SpecialColumnVO>
     */
    @Override
    public IPage<SpecialColumnVO> searchColumnPage(int pageNum, int pageSize) {
        // 构造分页构造器
        IPage<SpecialColumnVO> page = new Page<>(pageNum,pageSize);

        // 分页参数预处理
        pageNum = (pageNum - 1) * pageSize;

        // 分页查询
        List<SpecialColumn> voList = Optional
                .ofNullable(specialColumnMapper.selectSpecialColumnPage(pageNum, pageSize))
                .orElse(new ArrayList<>());

        // 转换VO
        List<SpecialColumnVO> specialColumnVOList = voList.stream()
                .map(this::toSpecialColumnVO).collect(Collectors.toList());

        // 查询总条数
        int total = specialColumnMapper.selectCountSpecialColumn();

        // 封装page
        page.setRecords(specialColumnVOList);
        page.setTotal(total);

        return page;
    }

    /**
     * 修改专栏状态
     * @param statusParam 专栏状态参数
     * @return 提示信息
     */
    @Transactional
    @Override
    public String updateSpecialColumnStatus(SpecialColumnStatusParam statusParam) {
        // 获取登录id
        long updateBy = Long.parseLong(StpUtil.getLoginId().toString());
        try {
            int count = specialColumnMapper.updateStatusById(statusParam.getStatus(),updateBy,statusParam.getId());
            if (count < 1)
                throw new CustomerException(Constants.PARAM_ERROR,"修改无效");
        } catch (Exception e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }
        return "修改成功";
    }

    /**
     * 新增专栏信息
     * @param specialColumnParam 保存的专栏参数
     * @return 提示信息
     */
    @Transactional
    @Override
    public String addSpecialColumn(SaveSpecialColumnParam specialColumnParam) {
        String addName = specialColumnParam.getName(); // 获取要保存的名称
        String addCoverImage = specialColumnParam.getCoverImage(); // 获取要保存的封面图片
        Long addCreateBy = specialColumnParam.getCreateBy(); // 获取要保存的创建人

        // 封装专栏
        SpecialColumn column = new SpecialColumn();
        column.setName(addName);
        column.setCoverImage(addCoverImage);
        column.setStatus(0);
        column.setCreateBy(addCreateBy);
        column.setUpdateBy(addCreateBy);

        // 新增
        int count = specialColumnMapper.insert(column);

        if (count < 1)
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);

        return "添加成功";
    }
}




